package com.cn.jx.manager.service.mtn.Impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cn.jx.common.service.BaseService;
import com.cn.jx.manager.dao.DictDataRepository;
import com.cn.jx.manager.po.DictData;
import com.cn.jx.manager.service.mtn.IDictServiceMtn;
import com.jx.enumType.ApplyEnum;
import com.jx.enumType.EmployeeTypeEnum;
import com.jx.enumType.ResourceTypeEnum;
import com.jx.enumType.SexEnum;
import com.jx.enumType.SwitchEnum;
import com.jx.enumType.YesNoEnum;
import com.jx.model.Dict;
import com.jx.util.Utility;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月1日
 * <p>功能描述：
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Service("dictServiceMtn") 
@Transactional
public class DictServiceImplMtn extends BaseService implements IDictServiceMtn {

	@Autowired
	private DictDataRepository dictDataDao;

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public DictData saveDictData(DictData item) {
		return dictDataDao.save(item);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void saveDictInit() {
		//APP应用
		saveDictSet(ApplyEnum.getAllEnum(),"所属应用","APP_ENUM");
		
		//员工类型
		saveDictSet(EmployeeTypeEnum.getAllEnum(),"员工类型","EMP_TYPE_ENUM");
		
		//资源
		saveDictSet(ResourceTypeEnum.getAllEnum(),"资源类型","RES_TYPE_ENUM");
		
		//性别
		saveDictSet(SexEnum.getAllEnum(),"性别","SEX_ENUM");
		
		//是否
	    saveDictSet(YesNoEnum.getAllEnum(),"是否","YON_ENUM");
	    
	   //开关
	    saveDictSet(SwitchEnum.getAllEnum(),"开关","SWITCH_ENUM");
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void saveDictSet(Set<Dict> set,String parentName,String type) {
		String parentId="";
		List<String> codes=dictDataDao.findDictValueByType(type);
		if(!codes.contains(type)){
			DictData ddparent=DictData.getInstance("system");
			ddparent.setLevel(0);
			ddparent.setName(parentName);
			ddparent.setDictType(type);
			ddparent.setValue(type);
			DictData parent=saveDictData(ddparent);
			parentId=parent.getId();
		}
		for(Dict d:set){
			if(!codes.contains(d.getId())){
				if(Utility.isBlank(parentId)){
					//空表示包含父类型 第一次循环陌生子类型 获取父类型的id
					parentId=dictDataDao.findIdByCode(type);
				}
				if(Utility.isNotBlank(parentId)){
					DictData dd=DictData.getInstance("system");
					dd.setLevel(1);
					dd.setName(d.getText());
					dd.setDictType(type);
					dd.setValue(d.getId());
					dd.setParent(parentId);
					saveDictData(dd);
				}
			}
		}
	}
}
